#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.
#************************BEGIN Add Include Files to Path************************
StakerWorkOrderid=224
PricesFileName='/home/coopgisadmin/Desktop/prices.csv'


TotalInstallPrice=[0]
TotalRemovePrice=[0]

import sys
IncludePath="/opt/coopgis/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
import csv
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *

#********************Setup psycopg2 and django section********************


#Data Structure example:  
#Dictionary['A1'] = [RemovePrice, InstallPrice]
def ReadPrices(FileName):
    Prices={}
    File=open(FileName, 'rb')
    reader=csv.reader(File)
    Rows=[]
    for row in reader:
        Rows.append(row)
    File.close()
    for row in Rows:
        if(not Prices.has_key(row[0])):
            Prices[row[0]] = [0,0]
    for row in Rows:
        if len(row) > 1:
            if(row[1]):
                try:
                    Prices[row[0]][0] = int(row[1])
                except:
                    Prices[row[0]][0] = 0
        if len(row) > 2:
            if(row[2]):
                try:
                    Prices[row[0]][1] = int(row[2])
                except:
                    Prices[row[0]][1] = 0
    return Prices

def GetInstallAssemblies(stakerWorkOrder):
    """Returns Assemblies in Format Results['CompatibleUnitName']= Quantity"""
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).filter(InstallStatus__Name='Install')
    Results={}
    for i in Assemblies:
        if(not Results.has_key(i.CompatibleUnit.Name)):
            if(i.Station):
                Results[i.CompatibleUnit.Name]=1
            else:
                Results[i.CompatibleUnit.Name]=float(i.Span.Line.length)/1000
        elif(i.Station):
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + 1
        else:
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + (float(i.Span.Line.length)/1000)           
    return Results
    

def GetRemoveAssemblies(stakerWorkOrder):
    """Returns Assemblies in Format Results['CompatibleUnitName']= Quantity"""
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).filter(InstallStatus__Name='Remove')
    Results={}
    for i in Assemblies:
        if(not Results.has_key(i.CompatibleUnit.Name)):
            if(i.Station):
                Results[i.CompatibleUnit.Name]=1
            else:
                Results[i.CompatibleUnit.Name]=float(i.Span.Line.length)/1000
        elif(i.Station):
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + 1
        else:
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + (float(i.Span.Line.length)/ 1000)           
    return Results


def GetInstallPrice(Prices, CompatibleUnitName, Quantity):
    if(Prices.has_key(CompatibleUnitName)):
        if(Prices[CompatibleUnitName][1]):
            TotalInstallPrice[0]=TotalInstallPrice[0] + Quantity * int(Prices[CompatibleUnitName][1]) 
            return str(int(Quantity * Prices[CompatibleUnitName][1]))
        else:
            return 'No Install Price'
    else:
        return 'No Match For Unit'

def GetRemovePrice(Prices, CompatibleUnitName, Quantity):
    if(Prices.has_key(CompatibleUnitName)):
        if(Prices[CompatibleUnitName][0]):
            TotalRemovePrice[0]=TotalRemovePrice[0] + Quantity * int(Prices[CompatibleUnitName][0])
            return str(int(Quantity * Prices[CompatibleUnitName][0]))
        else:
            return 'No Remove Price'
    else:
        return 'No Match For Unit'
    

def PopulateDatabase(Prices, company, StartDate, EndDate, Multiplier, Adder):
    #Dictionary['A1'] = [RemovePrice, InstallPrice]
    Total = len(Prices)
    Count = 0
    for i in Prices:
        command=Command()
        try:
            compatibleunit=CompatibleUnit.objects.filter(Name=i)[0]
        except:
            continue
        if(Prices[i][1]):
            CodedInstallPrice=(Prices[i][1] + Adder) * Multiplier
        else:
            CodedInstallPrice='Default'
        if(Prices[i][0]):
            CodedRemovePrice=(Prices[i][0] + Adder) * Multiplier
        else:
            CodedRemovePrice='Default'
        try:
            ExistingPrice=CompatibleUnitPrice.objects.filter(CompatibleUnit__Name=i)[0]
        except:
            ExistingPrice=None
        if(ExistingPrice):
            if(CodedInstallPrice == 'Default'):
                CodedInstallPrice=ExistingPrice.CodedInstallPrice
            if(CodedRemovePrice == 'Default'):
                CodedRemovePrice=ExistingPrice.CodedRemovePrice
        else:
            if(CodedInstallPrice == 'Default'):
                CodedInstallPrice = (0.0 + Adder) * Multiplier
            if(CodedRemovePrice == 'Default'):
                CodedRemovePrice = (0.0 + Adder) * Multiplier
        if(not ExistingPrice):
            command=command.Create(Name='CreateCompatibleUnitPrice', CommandUserName='robyg', CodedInstallPrice=CodedInstallPrice,
                           CodedRemovePrice=CodedRemovePrice, StartDate=StartDate, EndDate=EndDate, Companyid=company.id, CompatibleUnitName=compatibleunit.Name )
            command.save()
            command.Process()
        else:
            command=command.Create(Name='EditCompatibleUnitPrice', CommandUserName='robyg', CodedInstallPrice=CodedInstallPrice, CodedRemovePrice=CodedRemovePrice, 
                                   StartDate=StartDate, EndDate=EndDate)
            command.save()
            command.Process()
        Count = Count + 1
        if(Count % 25 == 0):
            print "On:  " + str(Count) + '     of     ' + str(Total)


def Run(Multiplier, Adder):
    Prices=ReadPrices(PricesFileName)
    company=Company.objects.filter(Name='Lee')[0]
    import datetime
    StartDate=datetime.datetime(2008, 1, 1)
    EndDate=datetime.datetime(2010,12,31)
    PopulateDatabase(Prices, company, StartDate, EndDate, Multiplier=Multiplier,
                     Adder=Adder)

#Need to access a Staker Work Order

#stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=StakerWorkOrderid)[0]
#InstallList = GetInstallAssemblies(stakerWorkOrder)
#RemoveList = GetRemoveAssemblies(stakerWorkOrder)
#print "**************************Install Costs**************************"
#for i in InstallList:
#    Quantity=InstallList[i]
#    if('.' in str(Quantity)):
#        Quantity=round(Quantity, 3) 
#    print i + ', $' + GetInstallPrice(Prices, i, InstallList[i]) + ',' + str(Quantity)
#print "\n\n\n\n" 
#print "**************************Remove Costs**************************"
#print
#for i in RemoveList:
#    Quantity=RemoveList[i]
#    if('.' in str(Quantity)):
#        Quantity=round(Quantity, 3) 
#    print i + ', $' + GetRemovePrice(Prices, i, RemoveList[i]) + ',' + str(Quantity)

#print "Total Install Cost:  " + str(round(TotalInstallPrice[0], 2)) +\
#      "   Total Remove Cost:  " + str(round(TotalRemovePrice[0], 2)) +\
#      "  Total:  " + str(round(TotalInstallPrice[0] + TotalRemovePrice[0], 2))

